package cn.rkylin.oms.aftersale.sysreturn.service.impl;

import static java.util.UUID.randomUUID;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.aftersale.resend.domain.AfterSaleResend;
import cn.rkylin.oms.aftersale.resend.domain.AfterSaleResendSku;
import cn.rkylin.oms.aftersale.resend.service.IAfterSaleResendService;
import cn.rkylin.oms.aftersale.sysrefund.domain.SysRefundSku;
import cn.rkylin.oms.aftersale.sysrefund.servcie.ISysRefundService;
import cn.rkylin.oms.aftersale.sysrefund.vo.SysRefundVO;
import cn.rkylin.oms.aftersale.sysreturn.dao.ISysReturnDAO;
import cn.rkylin.oms.aftersale.sysreturn.dao.ISysReturnSkuDAO;
import cn.rkylin.oms.aftersale.sysreturn.domain.SysReturn;
import cn.rkylin.oms.aftersale.sysreturn.domain.SysReturnSku;
import cn.rkylin.oms.aftersale.sysreturn.service.ISysReturnService;
import cn.rkylin.oms.aftersale.sysreturn.vo.ReturnInfoVO;
import cn.rkylin.oms.aftersale.sysreturn.vo.SysReturnSkuVO;
import cn.rkylin.oms.aftersale.sysreturn.vo.SysReturnVO;
import cn.rkylin.oms.common.consts.StatusConsts;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.order.dao.IOrderDAO;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderSkuVO;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.service.IShopStorService;
import cn.rkylin.oms.system.shop.vo.ShopStorVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.storage.dao.IStorDAO;
import cn.rkylin.oms.system.storage.vo.StorVO;
import cn.rkylin.oms.warehouse.returnStockin.service.IReturnStockinService;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinSkuVO;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinVO;
import cn.rkylin.oms.warehouse.shiporder.util.SnCodeExtractor;
import cn.rkylin.oms.warehouse.stockin.dao.StockInDAO;
import cn.rkylin.oms.warehouse.stockin.dao.StockInGoodsDAO;
import cn.rkylin.oms.warehouse.stockin.domain.StockIn;
import cn.rkylin.oms.warehouse.stockin.domain.StockInGoods;

/**
 * 类名:SysReturnServiceImpl <br/>
 * 作用: 退货单服务层实现类. <br/>
 * 创建原因: 退货单服务层实现类. <br/>
 * 创建时间: 2017年9月26日 下午8:48:45 <br/>
 *
 * @author zhanghao
 * @version v1.0
 */
@Service("sysReturnService")
public class SysReturnServiceImpl implements ISysReturnService {
    private static final Log logger = LogFactory.getLog(SysReturnServiceImpl.class);
    /**
     * sysReturnDAO:退货单数据层对象.
     */
    @Autowired
    ISysReturnDAO sysReturnDAO;
    
    @Autowired
    private SnCodeExtractor snCodeExtractor;
    /**
     * sysReturnSkuDAO:退货单明细数据层对象.
     */
    @Autowired
    ISysReturnSkuDAO sysReturnSkuDAO;

    /**
     * sysRefundService:退款单业务实现类.
     */
    @Autowired
    ISysRefundService sysRefundService;
    
    @Autowired
    IShopService shopService;

    @Autowired
    IOrderService orderService;

    @Autowired
    private StockInDAO stockInDAO;

    @Autowired
    private StockInGoodsDAO stockInGoodsDAO;

    @Autowired
    private IReturnStockinService returnStockinService;
    @Autowired
    private ProjectManagerService projectManagerService;
    @Autowired
    private IShopStorService shopStorService;;
    
    /**
     * 仓库数据访问对象
     */
    @Autowired
    private IStorDAO istorDAO;

    @Autowired
    private IOrderDAO orderDAO;

    @Autowired
    private IAfterSaleResendService resendService;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    /**
     * 查询退货单列表.
     *
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#querySysReturnVOList(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    public List<SysReturnVO> querySysReturnVOList(SysReturnVO sysReturn) throws Exception {
        List<SysReturnVO> sysReturnVOList = new ArrayList<SysReturnVO>();
        sysReturnVOList = sysReturnDAO.selectBySelectiveValue(sysReturn);
        return sysReturnVOList;
    }

    /**
     * 生成退货单和退货单明细.
     *
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#generateReturn(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    @Transactional
    public int generateReturn(SysReturnVO sysReturn) throws Exception {
        int returnValue = 0;

        SysReturnVO record = new SysReturnVO();
        BeanUtils.copyProperties(sysReturn, record);
        record.setReturnStatus(StatusConsts.AWAIT);
        record.setDeleted(YesNoConst.NO);
        record.setSourceId(sysReturn.getSourceId());
        record.setSourceCode(sysReturn.getSourceCode());

        record.setIsOperable(YesNoConst.YES);
        int updateCount = sysReturnDAO.updateBySelective(record);

        if (updateCount == 1) {
            // 存在可操作的退货单，将不存在于退货单上的商品添加到退货单明细里
            for (SysReturnSku sysReturnSku : sysReturn.getSysReturnSku()) {
                sysReturnSkuDAO.insertNotExistSku(sysReturnSku);
            }
        } else if (updateCount == 0) {
            // 不存在可操作的退货单,新增退货单退货商品明细
            sysReturnDAO.insertSelective(sysReturn);
            for (SysReturnSku sysReturnSku : sysReturn.getSysReturnSku()) {
                sysReturnSkuDAO.insert(sysReturnSku);
            }
            // TODO:包含对应订单上的赠品信息
        } else {
            logger.error("系统错误，针对一条退款单出现了多条可操作的退货单，不执行任何操作");
        }
        return returnValue;
    }

    /**
     * 退货单更新.
     *
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#updateSysReturn(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    public int updateSysReturn(SysReturnVO param) throws Exception {
        return sysReturnDAO.updateBySelective(param);
    }

    /**
     * 废弃三方仓退货单.
     *
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#cancelSysReturn4Ext(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    public int cancelSysReturn4Ext(SysReturnVO param) throws Exception {
        return sysReturnDAO.cancelSysReturn4Ext(param);

    }

    /**
     * 废弃本地仓退货单
     *
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#cancelSysReturn4Local(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    public int cancelSysReturn4Local(SysReturnVO param) throws Exception {
        return sysReturnDAO.cancelSysReturn4Local(param);
    }

    /**
     * 根据自动创建的退货单ID删除退货单明细.
     *
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#deleteReturnSkuByAutoReturnId(java.lang.String)
     */
    @Override
    public int deleteReturnSkuByAutoReturnId(String returnId) throws Exception {
        return sysReturnSkuDAO.deleteByAutoSysReturnID(returnId);
    }

    /**
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#updateUnApproveSysReturn(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    public int updateUnApproveSysReturn(SysReturnVO param) throws Exception {
        return sysReturnDAO.updateUnApproveSysReturn(param);
    }

    /**
     * @throws Exception
     * @see cn.rkylin.oms.sysreturn.service.ISysReturnService#querySysReturnVOListWithExtend(cn.rkylin.oms.sysreturn.vo.SysReturnVO)
     */
    @Override
    public List<SysReturnVO> querySysReturnVOListWithExtend(SysReturnVO queryParam) throws Exception {
        List<SysReturnVO> sysReturnVOList = new ArrayList<SysReturnVO>();
        sysReturnVOList = sysReturnDAO.selectBySelectiveValueExtend(queryParam);
        return sysReturnVOList;
    }

    /**
     * 按条件查询退货单信息列表(分页)
     *
     * @param page
     * @param length
     * @param queryParamVO
     * @return
     * @throws Exception
     */
    public PageInfo<SysReturnVO> getSysReturnListByCondition(int page, int length, SysReturnVO queryParamVO) throws Exception {
        PageInfo<SysReturnVO> returnValue = null;
        try {
            //Tab页状态判断
            if (StringUtils.isNotBlank(queryParamVO.getQueryStatus())) {
                String strQueryStatus = queryParamVO.getQueryStatus();
                //待审核
                if ("waitingAuth".equals(strQueryStatus)) {
                    queryParamVO.setReturnStatus("a");
                    queryParamVO.setIsCancel("w");//取消状态不等于 : y
                }
                //待收货
                if ("waitingReceive".equals(strQueryStatus)) {
                    queryParamVO.setReturnStatus("f");
                    queryParamVO.setIsCancel("w");//取消状态不等于 : y
                }
                //已完成
                if ("complete".equals(strQueryStatus)) {
                    queryParamVO.setReturnStatus("z");
                    queryParamVO.setIsCancel("w");//取消状态不等于 : y
                }
                //已废弃
                if ("cancel".equals(strQueryStatus)) {
                    queryParamVO.setIsCancel("y");//取消状态等于 : y
                }
            }
            //开始查询
            returnValue = sysReturnDAO.pageSelectByCondition(page, length, queryParamVO);

        } catch (Exception e) {
            logger.info("执行退货单查询出现错误".concat(e.getMessage()));
            throw e;
        }
        return returnValue;
    }

    /**
     * 通过ID获取单条退货单信息(带明细的)
     *
     * @param returnId
     * @return
     * @throws Exception
     */
    public SysReturnVO selectByPrimaryKey(String returnId) throws Exception {
        SysReturnVO returnValue = sysReturnDAO.selectByPrimaryKey(returnId);
        
        List<SysReturnSku> planReturnSkuList = returnValue.getSysReturnSku();
        for (SysReturnSku sysReturnSku : planReturnSkuList) {
            String snCode = getPlanSnCodeByReturnSku(sysReturnSku,returnValue);
            sysReturnSku.setSn(snCode);
        }
        
        return returnValue;
    }

    @Override
    public String getPlanSnCodeByReturnSku(SysReturnSku sysReturnSku,SysReturnVO returnValue) throws Exception {
        String snCode = StringUtils.EMPTY;
        String shipOrderType = StringUtils.EMPTY;
        if(YesNoConst.YES.equals(sysReturnSku.getIsOrderSku())) {
            // 如果退货的是订单
            shipOrderType = "or";
            snCode = snCodeExtractor.getSnCodeBySourceSkuId(sysReturnSku.getSourceSkuId(),shipOrderType,returnValue.getSourceId());
        }else{
            shipOrderType = "rs";
            
            // 获取补发单商品
            AfterSaleResendSku resendSku = resendService.selectResendSkubyresendSkuId(sysReturnSku.getSourceSkuId());
            if(resendSku!=null) {
                if(YesNoConst.YES.equalsIgnoreCase(resendSku.getIsOrderSku())) {
                    snCode = snCodeExtractor.getSnCodeBySourceSkuId(resendSku.getSourceSkuId(),shipOrderType,resendSku.getResendId());
                }else {
                    snCode = snCodeExtractor.getSnCodeBySourceSkuId(resendSku.getResendSkuId(),shipOrderType,resendSku.getResendId());
                }
            }
            
        }
        
        // 退货单计划退入上显示的sn号的数量需要与计划退入数相同
        String[] snCodeArray = snCode.split(",");
        int snCodeLength = Math.min(sysReturnSku.getQty(), snCodeArray.length);
        snCode = StringUtils.join(ArrayUtils.subarray(snCodeArray, 0, snCodeLength),",");
        return snCode;
    }
    
    

    /**
     * 通过ID获取单条退货单信息
     *
     * @param returnId
     * @return
     * @throws Exception
     */
    public SysReturnVO selectByPrimaryKeyOnly(String returnId) throws Exception {
        return sysReturnDAO.selectByPrimaryKeyOnly(returnId);
    }

    /**
     * 根据退款单生成退货单.
     *
     * @see cn.rkylin.oms.aftersale.sysreturn.service.ISysReturnService#generateReturnSysByRefund(java.lang.String)
     */
    @Override
    public void generateReturnSysByRefund(String sysRefundId) throws Exception {
        if (StringUtils.isNotEmpty(sysRefundId)) {
            SysRefundVO sysrefundVO = sysRefundService.getSysRefundDetailById(sysRefundId);

            // 根据退款单对象生成退货单
            SysReturnVO sysReturn = generateReturn(sysrefundVO);
            // 根据系统退款单明细信息生成退货单明细信息
            List<SysReturnSku> tempSysReturnskuList = generateReturnSkuList(sysrefundVO, sysReturn);
            sysReturn.setSysReturnSku(tempSysReturnskuList);

            generateReturn(sysrefundVO);
        }

    }

    /**
     * generateReturn:根据系统退款单，生成系统退货单对象. <br/>
     *
     * @param sysRefund 系统退款单对象，包含退款单明细信息
     * @throws Exception
     * @author zhanghao
     */
    private SysReturnVO generateReturn(SysRefundVO sysRefund) throws Exception {
        Date now = new Date();
        SysReturnVO sysReturnVO = new SysReturnVO();
        BeanUtils.copyProperties(sysRefund, sysReturnVO);

        sysReturnVO.setReturnId(getUUID());
        sysReturnVO.setReturnCode(generateReturnCode(sysRefund.getShopId()));
        sysReturnVO.setSourceId(sysRefund.getOrderId());
        sysReturnVO.setSourceCode(sysRefund.getOrderCode());
        sysReturnVO.setSourceType("or"); // 来源是订单

        sysReturnVO.setReturnStatus("a");

        OrderVO param = new OrderVO();
        param.setOrderId(sysRefund.getOrderId());
        List<OrderVO> orderList = orderService.getOrders(param);
        OrderVO order = new OrderVO();
        if (orderList.size() > 0) {
            order = orderList.get(0);
        }

        sysReturnVO.setCreateTime(now);
        sysReturnVO.setUpdateTime(now);

        sysReturnVO.setHasTaken(YesNoConst.NO);
        sysReturnVO.setLgstCode(sysRefund.getLgstNo());
        sysReturnVO.setLgstId(order.getLgstId());
        sysReturnVO.setLgstName(sysRefund.getLgstName());
        sysReturnVO.setStorCode(""); // 仓库号
        sysReturnVO.setStorId(order.getStorId());
        sysReturnVO.setStorName(order.getStorName());

        sysReturnVO.setEntId(sysRefund.getEntId());

        sysReturnVO.setIsAutoCreate(YesNoConst.NO);
        sysReturnVO.setIsCancel(YesNoConst.NO);
        sysReturnVO.setTradeCode(order.getTradeCode());

        // 退货单字段新增 - 开始
        sysReturnVO.setReturnReasonId(sysRefund.getRefundReasonId());   // 将系统退款原因ID写入退货单的退货原因ID
        sysReturnVO.setReturnReasonName(sysRefund.getRefundReasonName());   // 将系统退款原因类型写入退货单的退货原因

        sysReturnVO.setProvName(order.getProvName());   // 省
        sysReturnVO.setCityName(order.getCityName());   // 市
        sysReturnVO.setDistName(order.getDistName());   // 区
        // 退货单字段新增 - 结束


        return sysReturnVO;

    }

    /**
     * getUUID:主键生成方法. <br/>
     *
     * @return
     * @author zhanghao
     */
    private String getUUID() {
        String uuid = randomUUID().toString().replaceAll("-", StringUtils.EMPTY);
        return uuid;
    }

    /**
     * generateRefundCode:根据店铺ID生成退货单编码. <br/>
     *
     * @param shopId
     * @return
     * @throws Exception
     * @author zhanghao
     */
    private String generateReturnCode(String shopId) throws Exception {
        return generateReturnCodeWithType("RT", shopId);
    }

    /**
     * generateReturnCodeWithType:编码生成方法 <br/>
     *
     * @param codeType 编码类型
     * @param shopId   店铺ID
     * @return
     * @throws Exception
     * @author zhanghao
     */
    private String generateReturnCodeWithType(String codeType, String shopId) throws Exception {
        ShopVO shop = shopService.getShopById(shopId);
        ProjectVO project = projectManagerService.findProjectById(shop.getPrjId());
        String prjShortName = project.getPrjShortName();
        String returnCode = codeType + prjShortName + CodeUtil.getCode();
        return returnCode;
    }

    /**
     * generateReturnGoodsList:根据平台退款单和系统退款单，生成系统退货单明细. <br/>
     *
     * @param ecRefund  平台退款单对象
     * @param sysRefund 系统退款单对象，包含退款单明细信息
     * @param sysReturn 系统退货单对象
     * @author zhanghao
     */
    private List<SysReturnSku> generateReturnSkuList(SysRefundVO sysRefund, SysReturnVO sysReturn) {
        Date now = new Date();
        List<SysReturnSku> returnSkuList = new ArrayList<SysReturnSku>();

        List<SysRefundSku> sysRefundSkuList = sysRefund.getSysRefundSkuList();
        for (SysRefundSku sysRefundSku : sysRefundSkuList) {
            SysReturnSku tempReturnSku = new SysReturnSku();
            BeanUtils.copyProperties(sysRefundSku, tempReturnSku);

            tempReturnSku.setReturnSkuId(getUUID());
            tempReturnSku.setReturnId(sysReturn.getReturnId());
            tempReturnSku.setDeleted(YesNoConst.NO);

            tempReturnSku.setCreateTime(now);
            tempReturnSku.setUpdateTime(now);
            returnSkuList.add(tempReturnSku);

        }
        return returnSkuList;
    }

    /**
     * 获取退货单各个Tab页单据数量
     *
     * @param queryParamVO
     * @return
     * @throws Exception
     */
    public List<HashMap> findStateCount(SysReturnVO queryParamVO) throws Exception {
        List<HashMap> returnMap = sysReturnDAO.selectStateCount(queryParamVO);
        return returnMap;
    }

    /**
     * 系统退货单保存校验(包括新增和修改)
     *
     * @param returnInfoVO
     * @return
     * @throws Exception
     */
    private Map<String, String> checkReturnInfo(ReturnInfoVO returnInfoVO) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        // returnInfoVO为空
        if (returnInfoVO == null) {
            result.put("isOk", "n");
            result.put("errorMessage", "系统退货单VO为空");
            return result;
        }

        if (returnInfoVO.getSysReturnVO() == null) {
            result.put("isOk", "n");
            result.put("errorMessage", "系统退货单信息为空");
            return result;
        }
        SysReturnVO sysReturnVO = returnInfoVO.getSysReturnVO();

        // 原因类型不能为空
        if (StringUtils.isBlank(sysReturnVO.getRefundReasonId())
                || StringUtils.isBlank(sysReturnVO.getRefundReasonName())) {
            result.put("isOk", "n");
            result.put("errorMessage", "原因类型为空");
            return result;
        }
        // 发货人姓名不能为空
        if (StringUtils.isBlank(sysReturnVO.getCons())) {
            result.put("isOk", "n");
            result.put("errorMessage", "发货人姓名为空");
            return result;
        }
        // 发货人电话不能为空
        if (StringUtils.isBlank(sysReturnVO.getConsTel())
                && StringUtils.isBlank(sysReturnVO.getConsMobile())) {
            result.put("isOk", "n");
            result.put("errorMessage", "发货人电话和发货人手机至少填写一个");
            return result;
        }
//        //固定电话输入不正确
//        if (!isFixedPhone(sysReturnVO.getConsTel())) {
//            result.put("isOk", "n");
//            result.put("errorMessage", "发货人电话输入不正确");
//            return result;
//        }

//        // 发货人手机不能为空
//        if (StringUtils.isBlank(sysReturnVO.getConsMobile())) {
//            result.put("isOk", "n");
//            result.put("errorMessage", "发货人手机为空");
//            return result;
//        }
        //发货人手机输入不正确
        if (!StringUtils.isNumeric(sysReturnVO.getConsMobile())) {
            result.put("isOk", "n");
            result.put("errorMessage", "发货人手机输入不正确");
            return result;
        }
        //手机check暂时不按照号段进行检查
//        if (!isMobile(sysReturnVO.getConsMobile())) {
//            result.put("isOk", "n");
//            result.put("errorMessage", "发货人手机输入不正确");
//            return result;
//        }

        // 发货人地址不能为空
        if (StringUtils.isBlank(sysReturnVO.getConsAddr())) {
            result.put("isOk", "n");
            result.put("errorMessage", "发货人地址为空");
            return result;
        }
        // 入库仓库不能为空
        if (StringUtils.isBlank(sysReturnVO.getStorId())
                || StringUtils.isBlank(sysReturnVO.getStorName())) {
            result.put("isOk", "n");
            result.put("errorMessage", "入库仓库为空");
            return result;
        }

        //校验 仓库入库单号 是否存在
        if (StringUtils.isNotBlank(sysReturnVO.getWmsStockinCode())) {

            SysReturn sysReturnParam = new SysReturn();
            sysReturnParam.setReturnId(sysReturnVO.getReturnId());
            sysReturnParam.setWmsStockinCode(sysReturnVO.getWmsStockinCode());
            List<SysReturnVO> sysReturnVOList = sysReturnDAO.selectSysReturnWmsStockinCode(sysReturnParam);
            if (sysReturnVOList != null && sysReturnVOList.size() > 0) {
                result.put("isOk", "n");
                result.put("errorMessage", "仓库入库单号已存在，请重新填写");
                return result;
            }
        }



//--sku校验开始---------------------------------------------------
        if (returnInfoVO.getSysReturnSkuList() == null || returnInfoVO.getSysReturnSkuList().size() <= 0) {
            result.put("isOk", "n");
            result.put("errorMessage", "商品信息列表不能为空");
            return result;
        }
        if (returnInfoVO.getSysReturnSkuList() != null && returnInfoVO.getSysReturnSkuList().size() > 0) {
            List<SysReturnSkuVO> returnSkuList = returnInfoVO.getSysReturnSkuList();
            boolean blNoGoods = false;
            String cainiaoError = "";
            for (int returnSkuIndex = 0; returnSkuIndex < returnSkuList.size(); returnSkuIndex++) {
                SysReturnSkuVO vo = returnSkuList.get(returnSkuIndex);
                if ("n".equals(vo.getDeleted())) {
                    blNoGoods = true;

                    if (vo.getQty() == null || vo.getQty().intValue() <= 0) {
                        result.put("isOk", "n");
                        result.put("errorMessage", "退入数量不能为空或者小于等于零");
                        return result;
                    }
                    if (vo.getFactUnitPrice() == null
                            || vo.getFactUnitPrice().compareTo(BigDecimal.ZERO) == -1) {
                        result.put("isOk", "n");
                        result.put("errorMessage", "实际单价不能为空或者小于零");
                        return result;
                    }

                    //判断 如果仓库 是菜鸟仓库 商品信息需要是菜鸟商品
                    if (StringUtils.isNotBlank(sysReturnVO.getWmsStockinCode())) {

                        SysReturnSku sysReturnSkuParam = new SysReturnSku();
                        sysReturnSkuParam.setReturnSkuId(sysReturnVO.getShopId());
                        sysReturnSkuParam.setSkuId(vo.getSkuId());
                        List<SysReturnSku> sysReturnSkuCainiaoList = sysReturnSkuDAO.selectSysReturnSkuForCainiao(sysReturnSkuParam);
                        if (sysReturnSkuCainiaoList == null || sysReturnSkuCainiaoList.size() == 0) {
                            cainiaoError = cainiaoError + "规格商家编码："+vo.getSkuCode()+" \\n";
                        }
                    }

                }
            }
            if (blNoGoods == false) {
                result.put("isOk", "n");
                result.put("errorMessage", "商品信息列表不能为空");
                return result;
            }
            //系统商品是否关联菜鸟商品校验
            if (StringUtils.isNotBlank(cainiaoError)) {
                result.put("isOk", "s");
                result.put("errorMessage", "以下系统商品没有与菜鸟商品关联：\\n"+cainiaoError);
                return result;
            }
        }

        result.put("isOk", "y");
        result.put("errorMessage", "");
        return result;
    }

    /**
     * 保存系统退货单
     *
     * @param returnInfoVO
     * @param map
     * @return
     * @throws Exception
     */
    public Map<String, Object> saveSysReturns(ReturnInfoVO returnInfoVO, Map<String, String> map) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        //保存时的校验
        Map<String, String> checkMap = checkReturnInfo(returnInfoVO);
        if (!"y".equals(checkMap.get("isOk"))) {
            result.put("isOk", checkMap.get("isOk"));
            result.put("count", "0");
            result.put("errorMessage", checkMap.get("errorMessage"));
            return result;
        }

        int iRes = 0;
        SysReturnVO sysReturnVO = returnInfoVO.getSysReturnVO();//退货单基本信息
        List<SysReturnSkuVO> sysReturnSkuList = returnInfoVO.getSysReturnSkuList();//退货单商品信息
        if (StringUtils.isBlank(sysReturnVO.getLgstCode()) || StringUtils.isBlank(sysReturnVO.getLgstName())
                || "请选择".equals(sysReturnVO.getLgstName())) {
            sysReturnVO.setLgstId("");
            sysReturnVO.setLgstCode("");
            sysReturnVO.setLgstName("");
        }

        if ("insert".equals(returnInfoVO.getAction())) {
            //新增退货单
            SysReturn sysReturn = new SysReturn();
            BeanUtils.copyProperties(sysReturnVO, sysReturn);

            String strReturnId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            sysReturn.setPrjId(map.get("prjId"));
            sysReturn.setEntId(map.get("entId"));
            sysReturn.setReturnCode("RT" + map.get("prjShortName") + CodeUtil.getCode());
            sysReturn.setReturnId(strReturnId);
            
            //退货单插入数据库
            iRes = sysReturnDAO.insertSelective(sysReturn);
            if (iRes > 0) {
                //记录日志
                logUtil.info(new DBLog(sysReturn.getReturnCode(), "手动新增系统退货单", "手动新增系统退货单", "手动新增系统退货单成功"));
                //插入退货单商品明细到数据库
                for (int returnSkuIndex = 0; returnSkuIndex < sysReturnSkuList.size(); returnSkuIndex++) {
                    SysReturnSku sysReturnSku = sysReturnSkuList.get(returnSkuIndex);
                    sysReturnSku.setReturnSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                    sysReturnSku.setReturnId(strReturnId);
                    if ("是".equals(sysReturnSku.getIsGift())) {
                        sysReturnSku.setIsGift("y");
                    } else {
                        sysReturnSku.setIsGift("n");
                    }


//移动加权成本价计算 2018-1-12 wangxing add begin ------------------------------------------------------------------------------------------
                    //获取商品来源是订单和补发单的成本价
                    if (sysReturnSku.getIsOrderSku() != null && "y".equals(sysReturnSku.getIsOrderSku())) {
                        //来源订单
                        OrderSkuVO OrderSkuVOTemp = orderService.selectByPrimaryKeyOrderSku(sysReturnSku.getSourceSkuId());
                        if (OrderSkuVOTemp != null) {
                            sysReturnSku.setGoodsSkuCost(OrderSkuVOTemp.getGoodsSkuCost());
                        }
                    } else if (sysReturnSku.getIsOrderSku() != null && "r".equals(sysReturnSku.getIsOrderSku())) {
                        //来源补发单
                        AfterSaleResendSku afterSaleResendSku = resendService.selectResendSkubyresendSkuId(sysReturnSku.getSourceSkuId());
                        if (afterSaleResendSku != null) {
                            sysReturnSku.setGoodsSkuCost(afterSaleResendSku.getGoodsSkuCost());
                        }
                    } else {
                        //非单据商品成本价赋 零 。
                        sysReturnSku.setGoodsSkuCost(BigDecimal.ZERO);
                    }
//移动加权成本价计算 2018-1-12 wangxing add end --------------------------------------------------------------------------------------------


                    iRes = sysReturnSkuDAO.insert(sysReturnSku);
                }

                //更新系统订单退货单的状态
                OrderVO orderVOUpdate = new OrderVO();
                orderVOUpdate.setOrderId(sysReturn.getSourceId());
                orderVOUpdate.setHasReturn("y");
                int iOrderUpdate = orderDAO.update(orderVOUpdate);


            }
        } else {
            //修改退货单
            iRes = sysReturnDAO.updateBySelective(sysReturnVO);
            if (iRes > 0) {
                //记录日志
                logUtil.info(new DBLog(sysReturnVO.getReturnCode(), "手动修改系统退货单", "手动修改系统退货单", "手动修改系统退货单成功"));
                //修改退货单商品明细
                for (int returnSkuIndex = 0; returnSkuIndex < sysReturnSkuList.size(); returnSkuIndex++) {
                    SysReturnSkuVO sysReturnSku = sysReturnSkuList.get(returnSkuIndex);
                    sysReturnSku.setUpdateTime(new Date());
                    //修改商品处理 包括删除的商品
                    if ("update".equals(sysReturnSku.getAction())) {
                        //删除的商品
                        if ("y".equals(sysReturnSku.getDeleted())) {
                            SysReturnSku sysReturnSkuDelete = new SysReturnSku();
                            sysReturnSkuDelete.setDeleted("y");
                            sysReturnSkuDelete.setReturnSkuId(sysReturnSku.getReturnSkuId());
                            iRes = sysReturnSkuDAO.updateByPrimaryKeySelective(sysReturnSkuDelete);
                        } else {
                            //修改的商品
                            SysReturnSku sysReturnSkuUpdate = new SysReturnSku();
                            BeanUtils.copyProperties(sysReturnSku, sysReturnSkuUpdate);
                            iRes = sysReturnSkuDAO.updateByPrimaryKeySelective(sysReturnSkuUpdate);
                        }
                    } else if ("insert".equals(sysReturnSku.getAction())) {
                        //新增商品处理
                        sysReturnSku.setReturnSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                        sysReturnSku.setReturnId(sysReturnVO.getReturnId());
                        SysReturnSku sysReturnSkuInsert = new SysReturnSku();
                        BeanUtils.copyProperties(sysReturnSku, sysReturnSkuInsert);
                        if ("否".equals(sysReturnSkuInsert.getIsGift())) {
                            sysReturnSkuInsert.setIsGift("n");
                        } else if ("是".equals(sysReturnSkuInsert.getIsGift())) {
                            sysReturnSkuInsert.setIsGift("y");
                        } else {
                            sysReturnSkuInsert.setIsGift("n");
                        }
                        iRes = sysReturnSkuDAO.insert(sysReturnSkuInsert);
                    }
                }
            }
        }

        result.put("isOk", "y");
        result.put("count", "1");
        result.put("errorMessage", "");
        return result;
    }

    /**
     * updateReturnStorInfo:更新退货单中的退入仓库信息. <br/>
     *
     * @author zhanghao
     * @param sysReturnVO
     * @param sysReturn
     * @throws Exception
     */
    private void updateReturnStorInfo(SysReturnVO sysReturnVO, SysReturn sysReturn) throws Exception {
        ShopStorVO shopStorVO = new ShopStorVO();
        shopStorVO.setShopId(sysReturnVO.getShopId());
        shopStorVO.setStorId(sysReturnVO.getStorId());
        shopStorVO.setPrjId(sysReturnVO.getPrjId());
        // 如果订单发货仓有默认退货仓库，设置退货仓库；如果没有，就用订单的发货仓库
        List<ShopStorVO> shopStorList = shopStorService.getShopStorByCondition(shopStorVO);
        
        if(shopStorList.size()>0) {
            ShopStorVO shopStor = shopStorList.get(0);
            String returnStorId = shopStor.getReturnStorId();
            if(StringUtils.isNotEmpty(returnStorId)) {
                StorVO returnStor = (StorVO)istorDAO.findByid(returnStorId);
                if(null!=returnStor) {
                    sysReturn.setStorCode(returnStor.getStorCode());
                    sysReturn.setStorId(returnStor.getStorId());
                    sysReturn.setStorName(returnStor.getStorName());
                }
            }
        }
    }

    /**
     * 删除系统退货单
     *
     * @param returnIds
     * @return
     * @throws Exception
     */
    public int deleteSysReturn(String returnIds) throws Exception {
        SysReturnVO sysReturnVO = new SysReturnVO();
        sysReturnVO.setReturnId(returnIds);
        sysReturnVO.setDeleted("y");
        sysReturnVO.setUpdateTime(new Date());
        int iRes = sysReturnDAO.updateBySelective(sysReturnVO);
        if (iRes > 0) {
            //记录日志
            logUtil.info(new DBLog(returnIds, "手动删除退货单", "", "手动删除退货单成功"));

            //更新系统订单退货单的状态
            OrderVO orderVOUpdate = new OrderVO();
            //通过退货单id获取订单id
            SysReturnVO sysReturnVOForOne = sysReturnDAO.selectByPrimaryKeyOnly(returnIds);
            if (sysReturnVOForOne != null) {
                String strSourceId = sysReturnVOForOne.getSourceId();
                if (StringUtils.isNotBlank(strSourceId)) {
                    //通过来源id获取未废弃退货单信息
                    List<SysReturnVO> sysReturnVOBySourceID = sysReturnDAO.selectBySourceID(strSourceId);
                    if (sysReturnVOBySourceID == null || sysReturnVOBySourceID.size() <= 0) {
                        //没有 未废弃的退货单，更新订单退货单标识为 n
                        orderVOUpdate.setOrderId(strSourceId);
                        orderVOUpdate.setHasReturn("n");
                        int iOrderUpdate = orderDAO.update(orderVOUpdate);
                    }
                }
            }


        }
        return iRes;
    }

    /**
     * 通过系统退货单ID获取退货单商品信息
     *
     * @param returnId
     * @param orderId
     * @return
     * @throws Exception
     */
    public List<OrderSkuVO> selectByReturnId(String returnId, String orderId) throws Exception {
        List<OrderSkuVO> sysReturnSkuList = new ArrayList<OrderSkuVO>();
        List<SysReturnSku> returnSkuList = sysReturnSkuDAO.selectByReturnId(returnId);
        if (returnSkuList != null && returnSkuList.size() > 0) {
            //获取订单和补发单商品明细
//            List<OrderSkuVO> orderSkuList = orderService.getOrderSkuAndResendSkuByOrderId(orderId);
//循环退货单商品明细 returnSkuList 与订单商品明细ID判断哪些存在，存在的chk='y'，并把非单据的系统商品添加到显示列表中
            String strSourceSkuId = "";//订单商品明细Id
            for (SysReturnSku SysReturnSku : returnSkuList) {
                OrderSkuVO orderSkuVO = new OrderSkuVO();
                orderSkuVO.setReturnSkuId(SysReturnSku.getReturnSkuId());
                orderSkuVO.setIsOrderSku(SysReturnSku.getIsOrderSku());
                if ("y".equals(SysReturnSku.getIsOrderSku())) {
//                    orderSkuVO.setChk("y");
                    orderSkuVO.setSkuSource("订单");
                } else if ("r".equals(SysReturnSku.getIsOrderSku())) {
//                    orderSkuVO.setChk("y");
                    orderSkuVO.setSkuSource("补发单");
                } else {
                    orderSkuVO.setSkuSource("非单据");
                }
                orderSkuVO.setIsGift(SysReturnSku.getIsGift());

                orderSkuVO.setGoodsId(SysReturnSku.getGoodsId());
                orderSkuVO.setGoodsCode(SysReturnSku.getGoodsCode());
                orderSkuVO.setGoodsName(SysReturnSku.getGoodsName());
                orderSkuVO.setSkuId(SysReturnSku.getSkuId());
                orderSkuVO.setSkuCode(SysReturnSku.getSkuCode());
                orderSkuVO.setSkuName(SysReturnSku.getSkuName());

                orderSkuVO.setQty(SysReturnSku.getQty());
                orderSkuVO.setReturnQty(SysReturnSku.getQty());
                orderSkuVO.setFactUnitPrice(SysReturnSku.getFactUnitPrice());
                orderSkuVO.setFactMoney(SysReturnSku.getFactUnitPrice().multiply(BigDecimal.valueOf(SysReturnSku.getQty())));
                orderSkuVO.setRemark(SysReturnSku.getRemark());
                orderSkuVO.setDivideGoodsFee(SysReturnSku.getDivideGoodsFee());
                orderSkuVO.setOid(SysReturnSku.getEcOid());
                orderSkuVO.setOrderSkuId(SysReturnSku.getSourceSkuId());
                sysReturnSkuList.add(orderSkuVO);
            }
        }
        return sysReturnSkuList;
    }

    /**
     * 审核系统退货单校验，并可返回错误信息
     * 校验：退货快递单号和退回物流公司不能为空
     *
     * @param sysReturnId
     * @return
     * @throws Exception
     */
    @Override
    public String apprSysReturnCheck(String sysReturnId) throws Exception {
        JSONObject apprResult = new JSONObject();
        //校验
//        2、	退回的物流公司不能为空；
//        3、	退回的快递单号不能为空；
        //2和3 为是否继续审核的提示 ：  提示“退货单退回物流公司/退回快递单号为空，是否继续审核？

        //获取退货单的基本信息
        SysReturnVO sysReturnVO = sysReturnDAO.selectByPrimaryKeyOnly(sysReturnId);
        if (sysReturnVO != null) {
            if (StringUtils.isBlank(sysReturnVO.getLgstNo())
                    || StringUtils.isBlank(sysReturnVO.getLgstId())
                    || StringUtils.isBlank(sysReturnVO.getLgstName())) {
                apprResult.put("result", "failed");
            } else {
                apprResult.put("result", "success");
            }
        } else {
            apprResult.put("result", "failed");
        }

        return apprResult.toJSONString();
    }


    /**
     * 审核系统退货单，并可返回错误信息
     *
     * @param sysReturnId
     * @return
     * @throws Exception
     */
    @Override
    public String apprSysReturn(String sysReturnId, String prjShortName, String sysReturnCodes) throws Exception {
        JSONObject apprResult = new JSONObject();
        //校验
//        审核的条件：
//        1、	需要校验该退货单上的商品SKU是否已完成发货（该退货单所关联的订单/补发单是否有该退货商品SKU的已系统发货/平台发货的发货单），未完成发货的，审核失败并给出提示“单据编号+规格编码商品未发货”；
//        2、	退回的物流公司不能为空；
//        3、	退回的快递单号不能为空；

        //2和3 为是否继续审核的提示 ：  提示“退货单退回物流公司/退回快递单号为空，是否继续审核？

        //判断退货单的来源单据的发货单是否已发货
        List<SysReturnSku> returnSkuCheckCountList = sysReturnSkuDAO.apprCheckCountByReturnId(sysReturnId);
        if (returnSkuCheckCountList != null && returnSkuCheckCountList.size() <= 0) {
            List<SysReturnSku> returnSkuAllListRes = new ArrayList<>();
            List<SysReturnSku> returnSkuAllList = sysReturnSkuDAO.selectByReturnId(sysReturnId);
            if (returnSkuAllList != null && returnSkuAllList.size() > 0) {

                for (SysReturnSku SysReturnSkuFor : returnSkuAllList) {
//                    if (!"n".equals(SysReturnSkuFor.getIsOrderSku())) {
                    if ("y".equals(SysReturnSkuFor.getIsOrderSku())) {
                        returnSkuAllListRes.add(SysReturnSkuFor);
                    }
                }
                if (returnSkuAllListRes != null && returnSkuAllListRes.size() > 0) {
                    apprResult.put("result", "failed");
                    apprResult.put("detail", new JSONArray());
                    apprResult.getJSONArray("detail").add(returnSkuAllListRes);
                } else {
                    apprResult.put("result", "success");
                }
            }
        } else {
            //判断退货单的来源单据的发货单是否商品已经发货
            List<SysReturnSku> returnSkuCheckShiporderSkuList = sysReturnSkuDAO.apprCheckShiporderSkuByReturnId(sysReturnId);
            if (returnSkuCheckShiporderSkuList != null && returnSkuCheckShiporderSkuList.size() > 0) {
                apprResult.put("result", "failed");
                apprResult.put("detail", new JSONArray());
                apprResult.getJSONArray("detail").add(returnSkuCheckShiporderSkuList);
            } else {
                apprResult.put("result", "success");
            }
        }

        if ("success".equalsIgnoreCase(apprResult.getString("result"))) {
        	// 退货单code
        	String strStockinCode = "SI" + prjShortName + CodeUtil.getCode();
            
            //审核校验通过后，将该退货单状态由待审核状态转换为待收货状态。并生产退货入库单。
            //更新退货单状态为待收货
            SysReturnVO SysReturnVOUpdate = new SysReturnVO();
            SysReturnVOUpdate.setReturnId(sysReturnId);
            SysReturnVOUpdate.setWmsStockinCode(strStockinCode);
            SysReturnVOUpdate.setReturnStatus("f");
            SysReturnVOUpdate.setApprTime(new Date());
            SysReturnVOUpdate.setUpdateTime(new Date());
            int ires = sysReturnDAO.updateBySelective(SysReturnVOUpdate);
            if (ires > 0) {
                //记录日志
                logUtil.info(new DBLog(sysReturnCodes, "手动审核退货单", "手动审核退货单", "手动审核退货单成功"));
                //获取退货单的基本信息
                SysReturnVO sysReturnVO = sysReturnDAO.selectByPrimaryKey(sysReturnId);
                if (sysReturnVO != null) {
                    // 添加退货入库单 引用的是采购入库和其他入库单的实体类，一样的
                    StockIn stockIn = new StockIn();
                    String strStockinId = randomUUID().toString().replace("-", "");
                    stockIn.setStockinId(strStockinId);
                    stockIn.setStockinCode(strStockinCode);
                    stockIn.setEntId(sysReturnVO.getEntId());
                    stockIn.setEntId(sysReturnVO.getEntId());
                    stockIn.setPrjId(sysReturnVO.getPrjId());
                    stockIn.setStockinStatus("f");
                    stockIn.setUpdateTime(new Date());
                    stockIn.setStockinType("re");
                    stockIn.setPlanInTime(new Date());
                    stockIn.setStorId(sysReturnVO.getStorId());
                    stockIn.setStorCode(sysReturnVO.getStorCode());
                    stockIn.setStorName(sysReturnVO.getStorName());
                    stockIn.setLgstId(sysReturnVO.getLgstId());
                    stockIn.setLgstName(sysReturnVO.getLgstName());
                    stockIn.setLgstNo(sysReturnVO.getLgstNo());
                    stockIn.setDeliveryman(sysReturnVO.getCons());
                    stockIn.setDeliverymanMobile(sysReturnVO.getConsMobile());
                    stockIn.setDeliverymanTel(sysReturnVO.getConsTel());
                    stockIn.setRemark(sysReturnVO.getRemark());
                    stockIn.setSourceId(sysReturnVO.getReturnId());
                    stockIn.setSourceCode(sysReturnVO.getReturnCode());
                    stockIn.setTradeCode(sysReturnVO.getTradeCode());
                    stockIn.setReturnReasonName(sysReturnVO.getReturnReasonName());
                    stockIn.setWmsStockinCode(sysReturnVO.getWmsStockinCode());

                    int insertCount = stockInDAO.insertStockIn(stockIn);
                    if (insertCount > 0) {
                        //记录日志
                        logUtil.info(new DBLog(stockIn.getStockinCode(), "手动审核退货单生成退货入库单", "手动审核退货单生成退货入库单", "手动审核退货单生成退货入库单成功"));
                        // 添加入库单商品
                        List<SysReturnSku> returnSkuList = sysReturnVO.getSysReturnSku();
                        if (returnSkuList != null && returnSkuList.size() > 0) {
                            for (int returnSkuIndex = 0; returnSkuIndex < returnSkuList.size(); returnSkuIndex++) {
                                SysReturnSku sysReturnSku = returnSkuList.get(returnSkuIndex);
                                StockInGoods stockInGoods = new StockInGoods();

                                stockInGoods.setStockinSkuId(randomUUID().toString().replace("-", ""));
                                stockInGoods.setStockinId(strStockinId);
                                stockInGoods.setUpdateTime(new Date());
                                stockInGoods.setGoodsId(sysReturnSku.getGoodsId());
                                stockInGoods.setGoodsCode(sysReturnSku.getGoodsCode());
                                stockInGoods.setGoodsName(sysReturnSku.getGoodsName());
                                stockInGoods.setSkuId(sysReturnSku.getSkuId());
                                stockInGoods.setSkuCode(sysReturnSku.getSkuCode());
                                stockInGoods.setSkuName(sysReturnSku.getSkuName());
                                stockInGoods.setQty(sysReturnSku.getQty());
                                stockInGoods.setRemark(sysReturnSku.getRemark());
                                stockInGoods.setSourceId(sysReturnVO.getReturnId());//来源单据主表ID,即退货单ReturnId
                                stockInGoods.setFactUnitPrice(sysReturnSku.getFactUnitPrice());
                                stockInGoods.setDivideGoodsFee(sysReturnSku.getDivideGoodsFee());
                                stockInGoods.setIsGift(sysReturnSku.getIsGift());
                                stockInGoods.setGoodsSkuCost(sysReturnSku.getGoodsSkuCost());
                                stockInGoods.setSourceSkuId(sysReturnSku.getReturnSkuId());
                                stockInGoodsDAO.insertStockInGoods(stockInGoods);
                            }
                        }
                    } else {
                        apprResult.put("result", "errors");
                    }
                } else {
                    apprResult.put("result", "errors");
                }
            } else {
                apprResult.put("result", "errors");
            }
        }
        return apprResult.toJSONString();
    }

    /**
     * 取消系统退货单，并可返回错误信息
     *
     * @param sysReturnId
     * @return
     * @throws Exception
     */
    @Override
    public String cancelSysReturn(String sysReturnId) throws Exception {
        JSONObject cancelResult = new JSONObject();
        //校验
        //需要判断该退货入库单的状态，若为待收货状态，则直接取消退货入库单，对应的退货单也直接取消；
        // 若退货入库单的状态为收货中状态，则对应的退货入库单执行申请取消操作(调用已有的方法即可)，取消成功后，退货单也取消成功，反之则同为失败。
        //获取退货入库单信息
        ReturnStockinVO returnStockinVO = returnStockinService.getReturnStockInInfoBySourceId(sysReturnId);
        if (returnStockinVO != null) {
            //退货入库单为  待收货或收货中
            if ("f".equals(returnStockinVO.getStockinStatus())
                    && !"y".equals(returnStockinVO.getCancelStatus())) {
                Map<String, String> resultMap = null;
                try {
                    resultMap = returnStockinService.cancelReturnStockin(returnStockinVO.getStockinId());
                } catch (Exception ex) {
                    resultMap = null;
                }
                if (resultMap != null && resultMap.size() > 0) {
//                    if ("success".equals(resultMap.get("flag"))) {
                    if ("true".equals(resultMap.get("success"))) {
                        //记录日志
                        logUtil.info(new DBLog(returnStockinVO.getStockinId(), "手动取消退货单", "", "手动取消退货单成功，取消退货入库单成功"));
                        SysReturnVO SysReturnVOUpdate = new SysReturnVO();
                        SysReturnVOUpdate.setReturnId(sysReturnId);
                        SysReturnVOUpdate.setIsCancel("y");
                        SysReturnVOUpdate.setUpdateTime(new Date());
                        int ires = sysReturnDAO.updateBySelective(SysReturnVOUpdate);
                        if (ires > 0) {
                            //记录日志
                            logUtil.info(new DBLog(sysReturnId, "手动取消退货单", "", "手动取消退货单成功"));

                            //更新系统订单退货单的状态
                            OrderVO orderVOUpdate = new OrderVO();
                            //通过退货单id获取订单id
                            SysReturnVO sysReturnVOForOne = sysReturnDAO.selectByPrimaryKeyOnly(sysReturnId);
                            if (sysReturnVOForOne != null) {
                                String strSourceId = sysReturnVOForOne.getSourceId();
                                if (StringUtils.isNotBlank(strSourceId)) {
                                    //通过来源id获取未废弃退货单信息
                                    List<SysReturnVO> sysReturnVOBySourceID = sysReturnDAO.selectBySourceID(strSourceId);
                                    if (sysReturnVOBySourceID == null || sysReturnVOBySourceID.size() <= 0) {
                                        //没有 未废弃的退货单，更新订单退货单标识为 n
                                        orderVOUpdate.setOrderId(strSourceId);
                                        orderVOUpdate.setHasReturn("n");
                                        int iOrderUpdate = orderDAO.update(orderVOUpdate);
                                    }
                                }
                            }

                            cancelResult.put("result", "success");
                        } else {
                            cancelResult.put("result", "failed");
                        }
                    } else {
                        //记录日志
                        logUtil.info(new DBLog(returnStockinVO.getStockinId(), "手动取消退货单", "", "手动取消退货单失败，取消退货入库单失败"));
                        if ("y".equals(returnStockinVO.getHasTaken())) {
                            //退货入库单已被拿走,更新取消失败原因
                            SysReturnVO SysReturnVOUpdate = new SysReturnVO();
                            SysReturnVOUpdate.setReturnId(sysReturnId);
                            SysReturnVOUpdate.setIsCancel("f");
                            SysReturnVOUpdate.setCancelRemark(resultMap.get("message").toString());
                            SysReturnVOUpdate.setUpdateTime(new Date());
                            int ires = sysReturnDAO.updateBySelective(SysReturnVOUpdate);
                            if (ires > 0) {
                                //记录日志
                                logUtil.info(new DBLog(sysReturnId, "手动取消退货单", "", "手动取消退货单失败"));
                            }
                        }
                        cancelResult.put("result", "failed");
                    }
                } else {
                    cancelResult.put("result", "failed");
                }
            }
        }

        return cancelResult.toJSONString();
    }

    /**
     * 区号+座机号码+分机号码
     *
     * @param fixedPhone
     * @return
     */
    private boolean isFixedPhone(String fixedPhone) {
        if (StringUtils.isBlank(fixedPhone)) {
            return true;
        }
        String reg = "^[0][1-9]{2,3}-[0-9]{5,10}$";
        return Pattern.matches(reg, fixedPhone);
    }

    /**
     * 验证手机号码（支持国际格式，+86135xxxx...（中国内地），+00852137xxxx...（中国香港））
     *
     * @param mobile 移动、联通、电信运营商的号码段
     *               <p>
     *               移动的号段：134(0-8)、135、136、137、138、139、147（预计用于TD上网卡）
     *               、150、151、152、157（TD专用）、158、159、187（未启用）、188（TD专用）
     *               </p>
     *               <p>
     *               联通的号段：130、131、132、155、156（世界风专用）、185（未启用）、186（3g）
     *               </p>
     *               <p>
     *               电信的号段：133、153、180（未启用）、189
     *               </p>
     * @return 验证成功返回true，验证失败返回false
     */
    private boolean isMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return true;
        }
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        return Pattern.matches(regex, mobile);
    }

    @Override
    public List<SysReturnVO> findSysReturnByOrderId(String orderId) throws Exception {
        return sysReturnDAO.selectBySourceID(orderId);
    }
    
    @Override
    public List<SysReturnSku> findSysReturnSkuByReturnSkuId(String returnSkuId) throws Exception {
    	return sysReturnSkuDAO.selectByReturnSkuIdSysReturnSku(returnSkuId);
    }

    @Override
    public int getUnGoingCount(Map<String, String> paramMap) throws Exception {
        return sysReturnDAO.getUnGoingCount(paramMap);
    }

    @Override
    public SysReturnSku selectSysReturnSkuByPrimaryKey(String returnSkuId) throws Exception {
        return sysReturnSkuDAO.selectByPrimaryKey(returnSkuId);
    }

}
